package com.tpvlog.dfs.namenode.server;

import com.tpvlog.dfs.namenode.file.FSNameSystem;
import com.tpvlog.dfs.namenode.log.EditLogReplicator;
import com.tpvlog.dfs.namenode.register.DataNodeManager;
import io.grpc.Server;
import io.grpc.ServerBuilder;

import java.io.IOException;

public class NameNodeRpcServer {
    private static final int DEFAULT_PORT = 50070;
    private Server server;

    // 负责管理元数据的核心组件
    private FSNameSystem namesystem;

    // 负责管理集群中所有的datanode的组件
    private DataNodeManager datanodeManager;

    // 负责日志复制的组件
    private EditLogReplicator editLogReplicator;

    public NameNodeRpcServer(FSNameSystem namesystem, DataNodeManager datanodeManager, EditLogReplicator replicator) {
        this.namesystem = namesystem;
        this.datanodeManager = datanodeManager;
        this.editLogReplicator = replicator;
    }

    public void start() throws IOException {
        // 启动一个rpc server，监听指定的端口号，同时绑定好服务
        server = ServerBuilder
                .forPort(DEFAULT_PORT)
                .addService(new NameNodeServiceImpl(namesystem, datanodeManager, editLogReplicator))
                .build()
                .start();

        System.out.println("NameNodeRpcServer启动，监听端口号：" + DEFAULT_PORT);

        // 停机钩子
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                NameNodeRpcServer.this.stop();
            }
        });
    }

    public void stop() {
        if (server != null) {
            server.shutdown();
        }
    }

    public void blockUntilShutdown() throws InterruptedException {
        if (server != null) {
            server.awaitTermination();
        }
    }

}